const query = require('../../models');
const jwt = require('jsonwebtoken');
const { jwtConfig } = require('../../config');
const { decryptPassword, encryptedPassword } = require('../../utils/md5');

module.exports = {
  login(req, res) {
    const sql = `select * from users where user_name=?`;
    const { username, password } = req.body;

    query(sql, [username])
      .then(result => {

        if (result.length > 0) {
          const nowPass = decryptPassword(password, result[0].user_pass.substr(0, 8));
          console.log('登录传递的密码加密：', nowPass);
          console.log('数据库取出来的加密密码：', result[0].user_pass);

          if (nowPass == result[0].user_pass) {
            const token = jwt.sign({ // 生成 token
              user_name: username
            }, jwtConfig.secretFront, { // 秘钥
              expiresIn: 60 * 60 // 过期时间
            });

            res.json({
              code: '200',
              errMsg: '登录成功',
              data: {
                userId: result[0].user_id,
                username: result[0].user_name,
                avator: result[0].avator_id,
                token
              }
            });
          } else {
            res.json({
              code: '1005',
              errorMsg: '账号或者密码错误'
            })
          }
        } else {
          res.json({
            code: '1005',
            errorMsg: '账号或者密码错误'
          })
        }
      })
      .catch(err => {
        res.json({
          code: '1001',
          errorMsg: '操作失败',
          err: err
        })
      });
  },
  async check(req, res) {
    const checkState = await checkUser(req.query.username);
    console.log('验证用户名是否存在的结果：', checkState);

    if (checkState) {
      res.json({
        code: '1001',
        msg: '该用户已存在'
      })
    } else {
      res.json({
        code: '200',
        msg: '该用户名可以使用'
      })
    }
  },
  async register(req, res) {
    const sql = `insert into users values(null,?,?,null,null,null,default)`;
    const { username, password } = req.body;

    const checkState = await checkUser(req.query.username);
    console.log('验证用户名是否存在的结果：', checkState);

    if (checkState) {
      return res.json({
        code: '1001',
        msg: '该用户已存在'
      })
    }

    const newPass = encryptedPassword(password); // 加密

    query(sql, [username, newPass])
      .then(result => {
        console.log('注册成功：', result);
        res.json({
          code: '200',
          errMsg: '注册成功'
        });
      })
      .catch(err => {
        res.json({
          code: '1001',
          errorMsg: '注册失败',
          err: err
        })
      });
  },
}

async function checkUser(username) {
  const sql = `select * from users where user_name=?`;

  const result = await query(sql, [username]);
  if (result.length > 0) {
    return true;
  } else {
    return false;
  }
}